<?php

namespace app\api\controller;

use addons\epay\library\Service;
use addons\qcloudsms\Qcloudsms;
use app\admin\model\ClubDtl;
use app\admin\model\Order;
use app\admin\model\order\Refunds;
use app\admin\model\TeacherClass;
use app\admin\model\TeacherDetail;
use app\common\controller\Api;
use app\common\library\Getui;
use app\common\model\Test;
use GatewayWorker\Lib\Gateway;
use think\Session;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Formatter;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test', 'test1','wxcallback','wxrefundcallback'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    function getWeekdayDate($weekday) {
        // 设置时区确保日期计算准确
        date_default_timezone_set('Asia/Shanghai');

        // 定义星期映射关系
        $weekday_map = [
            '周一' => 1, '星期一' => 1,'星期二' => 2, '周二' => 2, '星期三' => 3, '周三' => 3,
            '星期四' => 4, '周四' => 4, '星期五' => 5, '周五' => 5,
            '星期六' => 6, '周六' => 6, '星期日' => 7, '周日' => 7,'周天' => 7, '星期天' => 7
        ];

        // 检查传入的星期参数是否有效
        if (!isset($weekday_map[$weekday])) {
            return "错误：无效的星期参数，请使用如'周一'、'周二'等格式";
        }

        $current_weekday = date('w'); // 获取当前星期几，0为周日，1-6为周一到周六
        $target_weekday = $weekday_map[$weekday];

        // 修复逻辑：计算本周目标日期
        $day_diff = $target_weekday - $current_weekday;

        // 如果目标星期在当前星期之前，需要加上7天来获取本周日期
//        if ($day_diff < 0) {
            $day_diff += 7;
//        }
        // 使用strtotime计算目标日期
        $target_date = date('Y-m-d', strtotime("+{$day_diff} days"));

        return $target_date;
    }
    function calculateTargetDate($start_date, $target_weekday) {
        // 验证开始日期格式
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date)) {
            return "错误：开始日期格式不正确，请使用YYYY-MM-DD格式";
        }

        // 定义星期映射关系
        $weekday_map = [
            '周一' => 0, '星期二' => 1, '周二' => 1,
            '周三' => 2, '星期三' => 2,
            '周四' => 3, '星期四' => 3,
            '周五' => 4, '星期五' => 4,
            '周六' => 5, '星期六' => 5,
            '周日' => 6, '星期日' => 6, '周天' => 6,'星期天' => 6
        ];

        // 检查目标星期参数是否有效
        if (!isset($weekday_map[$target_weekday])) {
            return "错误：无效的星期参数，请使用如'周一'、'周二'等格式";
        }

        $target_weekday_num = $weekday_map[$target_weekday];

        // 获取开始日期的星期几（0为周日，1-6为周一到周六）
        $start_weekday = date('w', strtotime($start_date));
        // 将周日的0转换为6，统一为0-5表示周一到周六，6表示周日
        if ($start_weekday == 0) {
            $start_weekday = 6;
        } else {
            $start_weekday = $start_weekday - 1;
        }
        // 计算天数差
        $day_diff = $target_weekday_num - $start_weekday;

        // 如果目标星期在开始日期之前，需要加上7天来获取下一周的日期
        if ($day_diff < 0) {
            $day_diff += 7;
        }
        // 计算目标日期
        $target_date = date('Y-m-d', strtotime($start_date . " +{$day_diff} days"));

        return $target_date;
    }
    public function aa()
    {
        $start_date = '2025-12-06';
        $a = $this->calculateTargetDate($start_date, '周一');
        var_dump('周一'.$a);
        $a = $this->calculateTargetDate($start_date, '周二');
        var_dump('周二'.$a);
        $a = $this->calculateTargetDate($start_date, '周三');
        var_dump('周三'.$a);
        $a = $this->calculateTargetDate($start_date, '周四');
        var_dump('周四'.$a);
        $a = $this->calculateTargetDate($start_date, '周五');
        var_dump('周五'.$a);
        $a = $this->calculateTargetDate($start_date, '周六');
        var_dump('周六'.$a);
        $a = $this->calculateTargetDate($start_date, '周日');
        var_dump('周日'.$a);
        exit;

// 测试代码
        echo "当前日期：" . date('Y-m-d') . "（" . date('l') . "）\n\n";

        $test_weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

        foreach ($test_weekdays as $day) {
            $date = $this->getWeekdayDate($day);
            echo "{$day}：{$date}\n";
        }

// 函数调用示例
        if (isset($_GET['weekday'])) {
            $weekday = $_GET['weekday'];
            $result = $this->getWeekdayDate($weekday);

            header('Content-Type: application/json');
            echo json_encode([
                'weekday' => $weekday,
                'date' => $result,
                'current_date' => date('Y-m-d'),
                'current_weekday' => date('l')
            ]);
        }
    }
    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    function getTimePeriod($startTime, $endTime) {
        $startHour = (int)explode(':', $startTime)[0];
        $endHour = (int)explode(':', $endTime)[0];

        if ($startHour >= 6 && $endHour <= 12) {
            return "上午";
        } elseif ($startHour >= 12 && $endHour <= 18) {
            return "下午";
        } elseif ($startHour >= 18 && $endHour <= 24) {
            return "晚上";
        } else {
            // 跨时段情况处理
            if ($startHour < 12 && $endHour > 12) {
                return "上午-下午";
            } elseif ($startHour < 18 && $endHour > 18) {
                return "下午-晚上";
            } else {
                return "特殊时段";
            }
        }
    }

    public function teacher_qy(){

        // 数据迁移：从IdentityInfo复制数据到TeacherDetail
        try {
            // 获取所有教师身份信息
            $teachers = \app\admin\model\IdentityInfo::where(['identity_type' => '教师'])->select();

            $total = count($teachers);
            $success = 0;
            $skip = 0;

            echo "开始迁移数据，共 {$total} 条教师记录<br><br>";

            // 定义两个表的共同字段
            $commonFields = [
                'educational_back', 'work_experience', 'certificate_reward', 'self_assessment',
                'work_time', 'club_one_id', 'club_two_id', 'is_premium', 'tag_me',
                'hourly_rate', 'score', 'people', 'imgs', 'teacher_certification',
                'diploma', 'occupational_qualifications', 'professional_skill',
                'health_certificate', 'identity_card_img', 'no_crime',
                'course_outline', 'teaching_objectives', 'jxjh', 'addtime'
            ];

            foreach ($teachers as $teacher) {
                try {
                    // 检查是否已经存在该info_id的记录
                    $exists = \app\admin\model\TeacherDetail::where('info_id', $teacher['id'])->find();
                    if ($exists) {
                        echo "⏭️ 教师 {$teacher['name']} (ID: {$teacher['id']}) 已存在，跳过<br>";
                        $skip++;
                        continue;
                    }

                    // 构建插入数据
                    $insertData = ['info_id' => $teacher['id']];

                    foreach ($commonFields as $field) {
                        if (isset($teacher[$field])) {
                            $insertData[$field] = $teacher[$field];
                        }
                    }

                    // 插入新记录
                    $result = \app\admin\model\TeacherDetail::insert($insertData);

                    if ($result) {
                        $success++;
                        echo "✓ 教师 {$teacher['name']} (ID: {$teacher['id']}) 迁移成功<br>";
                    } else {
                        echo "✗ 教师 {$teacher['name']} (ID: {$teacher['id']}) 迁移失败<br>";
                    }
                } catch (\Exception $e) {
                    echo "✗ 教师 {$teacher['name']} (ID: {$teacher['id']}) 异常: {$e->getMessage()}<br>";
                }
            }

            echo "<br>=== 迁移完成 ===<br>";
            echo "总记录数: {$total}<br>";
            echo "成功迁移: {$success}<br>";
            echo "已跳过: {$skip}<br>";
            echo "失败数: " . ($total - $success - $skip) . "<br>";

        } catch (\Exception $e) {
            echo "迁移过程异常: " . $e->getMessage() . "<br>";
        }
    }

    public function test()
    {
        //调整数据 已下订单课程绑定教师课程id
        $detail = TeacherDetail::column('id','info_id');
        $class = TeacherClass::select();
        foreach ($class as $k=>$v){
            if(isset($detail[$v['teacher_id']])&&$detail[$v['teacher_id']]){
                TeacherClass::where(['id'=>$v['id']])->update(['teacher_detail_id'=>$detail[$v['teacher_id']]]);
            }
        }
        exit;
        // 数据迁移：从IdentityInfo复制数据到TeacherDetail
        try {
            // 获取所有教师身份信息
            $teachers = \app\admin\model\IdentityInfo::where(['identity_type' => '教师'])->select();
            
            $total = count($teachers);
            $success = 0;
            $skip = 0;
            
            echo "开始迁移数据，共 {$total} 条教师记录<br><br>";
            
            // 定义两个表的共同字段
            $commonFields = [
                'educational_back', 'work_experience', 'certificate_reward', 'self_assessment',
                'work_time', 'club_one_id', 'club_two_id', 'is_premium', 'tag_me',
                'hourly_rate', 'score', 'people', 'imgs', 'teacher_certification',
                'diploma', 'occupational_qualifications', 'professional_skill',
                'health_certificate', 'identity_card_img', 'no_crime',
                'course_outline', 'teaching_objectives', 'jxjh', 'addtime'
            ];
            
            foreach ($teachers as $teacher) {
                try {
                    // 检查是否已经存在该info_id的记录
                    $exists = \app\admin\model\TeacherDetail::where('info_id', $teacher['id'])->find();
                    if ($exists) {
                        echo "⏭️ 教师 {$teacher['name']} (ID: {$teacher['id']}) 已存在，跳过<br>";
                        $skip++;
                        continue;
                    }
                    
                    // 构建插入数据
                    $insertData = ['info_id' => $teacher['id']];
                    
                    foreach ($commonFields as $field) {
                        if (isset($teacher[$field])) {
                            $insertData[$field] = $teacher[$field];
                        }
                    }
                    
                    // 插入新记录
                    $result = \app\admin\model\TeacherDetail::insert($insertData);
                    
                    if ($result) {
                        $success++;
                        echo "✓ 教师 {$teacher['name']} (ID: {$teacher['id']}) 迁移成功<br>";
                    } else {
                        echo "✗ 教师 {$teacher['name']} (ID: {$teacher['id']}) 迁移失败<br>";
                    }
                } catch (\Exception $e) {
                    echo "✗ 教师 {$teacher['name']} (ID: {$teacher['id']}) 异常: {$e->getMessage()}<br>";
                }
            }
            
            echo "<br>=== 迁移完成 ===<br>";
            echo "总记录数: {$total}<br>";
            echo "成功迁移: {$success}<br>";
            echo "已跳过: {$skip}<br>";
            echo "失败数: " . ($total - $success - $skip) . "<br>";
            
        } catch (\Exception $e) {
            echo "迁移过程异常: " . $e->getMessage() . "<br>";
        }
        
        exit;
        // 获取所有教师
        $teachers = \app\admin\model\IdentityInfo::where(['identity_type' => '教师'])->select();
        
        $total = count($teachers);
        $success = 0;
        
        echo "开始推送队列任务，共 {$total} 位教师<br><br>";
        
        // 循环推送队列任务
        foreach ($teachers as $teacher) {
            try {
                $result = \think\Queue::push('app\\job\\GenerateTeacherWordJob', ['user_id' => $teacher['user_id']], 'default');
                if ($result) {
                    $success++;
                    echo "✓ {$teacher['name']} (ID: {$teacher['user_id']}) 推送成功<br>";
                }
            } catch (\Exception $e) {
                echo "✗ {$teacher['name']} (ID: {$teacher['user_id']}) 推送失败: {$e->getMessage()}<br>";
            }
        }
        
        echo "<br>推送完成！成功: {$success} / {$total}<br>";
        echo "<br>请启动队列监听: <code>php think queue:listen --queue default</code><br>";
        echo "或双击运行: <code>start_queue.bat</code><br>";
        
        exit;
        $sql = "SELECT * FROM fa_identity_info 
WHERE 
    (TIME(SUBSTRING_INDEX(appointment_time, ' - ', 1)) < '12:00:00' AND 
     TIME(SUBSTRING_INDEX(appointment_time, ' - ', -1)) > '06:00:00')";

        $a = \app\admin\model\IdentityInfo::whereRaw("(TIME(SUBSTRING_INDEX(appointment_time, ' - ', 1)) < '24:00:00' AND 
     TIME(SUBSTRING_INDEX(appointment_time, ' - ', -1)) > '18:00:00')")->select();

        $this->success('',$a);
        exit;
// 教师A：14:00-16:00
        $teacherA = $this->getTimePeriod('14:00', '16:00');
        echo "教师A上课时间：{$teacherA}时段\n";

// 教师B：10:00-14:00
        $teacherB = $this->getTimePeriod('10:00', '14:00');
        echo "教师B上课时间：{$teacherB}时段\n";







        exit;
        // 自动填充所有用户邀请码的脚本
        try {
            // 获取所有没有邀请码的用户
            $users = \app\admin\model\User::where('invitation_code', '')
                ->whereOr('invitation_code', 'null')
                ->whereOr('invitation_code', null)
                ->select();
            
            $count = 0;
            $successCount = 0;
            $errorCount = 0;
            $errors = [];
            
            foreach ($users as $user) {
                $count++;
                try {
                    // 生成唯一的邀请码
                    $invitationCode = \app\admin\model\User::generateInvitationCode();
                    
                    // 更新用户邀请码
                    $result = \app\admin\model\User::where('id', $user['id'])->update([
                        'invitation_code' => $invitationCode
                    ]);
                    
                    if ($result) {
                        $successCount++;
                        echo "用户ID: {$user['id']}, 用户名: {$user['username']}, 邀请码: {$invitationCode} - 更新成功\n";
                    } else {
                        $errorCount++;
                        $errors[] = "用户ID: {$user['id']}, 用户名: {$user['username']} - 更新失败";
                        echo "用户ID: {$user['id']}, 用户名: {$user['username']} - 更新失败\n";
                    }
                } catch (\Exception $e) {
                    $errorCount++;
                    $errors[] = "用户ID: {$user['id']}, 用户名: {$user['username']} - 异常: " . $e->getMessage();
                    echo "用户ID: {$user['id']}, 用户名: {$user['username']} - 异常: " . $e->getMessage() . "\n";
                }
            }
            
            // 输出统计结果
            echo "\n=== 脚本执行完成 ===\n";
            echo "总处理用户数: {$count}\n";
            echo "成功更新数: {$successCount}\n";
            echo "失败数: {$errorCount}\n";
            
            if (!empty($errors)) {
                echo "\n=== 错误详情 ===\n";
                foreach ($errors as $error) {
                    echo $error . "\n";
                }
            }
            
            // 验证结果
            $emptyCodeUsers = \app\admin\model\User::where('invitation_code', '')
                ->whereOr('invitation_code', 'null')
                ->whereOr('invitation_code', null)
                ->count();
            
            echo "\n=== 验证结果 ===\n";
            echo "剩余空邀请码用户数: {$emptyCodeUsers}\n";
            
            if ($emptyCodeUsers == 0) {
                echo "✅ 所有用户邀请码已成功填充！\n";
            } else {
                echo "⚠️ 仍有 {$emptyCodeUsers} 个用户邀请码为空\n";
            }
            
        } catch (\Exception $e) {
            echo "脚本执行异常: " . $e->getMessage() . "\n";
        }
        
        exit;
        $fail_reason = '';
        $all = $this->request->param();
        //腾讯云
        $params = [
            'template_id' => 2445619,
            'mobile' => 18279539321,
            'code'=>[]
        ];
        $Qcloudsms = new Qcloudsms();
        $res = $Qcloudsms->smsSend($params);
        if (!$res) {
            $fail_reason = $Qcloudsms->getError();
        }

        var_dump($fail_reason);
        exit;
        $a = (int)'周一';
        $b = 1;
        if(is_int($a)){
            var_dump(33);
        }else{
            var_dump(44);
        }
        exit;
        $arr = [
            '3D打印社',
            '无人机社',
            '机器人社',
            '创客发明社',
            '校园电视台',
        ];

        $asd = 83;
        $arrs = [];
        foreach ($arr as $k=>$v){
            $arrs[$k]['club_id'] = 5;
            $arrs[$k]['name'] = $v;
            $arrs[$k]['sort'] = $asd;
            $arrs[$k]['addtime'] = date('Y-m-d H:i:s');
            $asd--;
        }
        $a = ClubDtl::insertAll($arrs);
        exit;



//
//        $res = \app\common\library\Sms::send('18279539321','1234','register');
//        var_dump($res);
//        hook("register", ['template'=>"2424716", "mobile"=>'18279539321', '123456']);
        //腾讯云
        $params = [
            'template_id' => 2424712,
            'mobile' => 18279539321,
            'code' => '123456', //模板参数，不同模版有不同入参
        ];
        $Qcloudsms = new Qcloudsms();
        $res = $Qcloudsms->smsSend($params);
        var_dump($res);
        exit;

        /**
         *

         */
        $this->success('返回成功', ($message));
    }

    /**
     * 无需登录的接口
     *
     */
    public function test1()
    {
        $this->success('返回成功', ['action' => 'test1']);
    }
    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $user = $this->auth->getUser();
        $this->success('返回成功', $user);
    }


    //微信支付回调
    public function wxcallback(){
        $all = $this->request->param();
        $header = $this->request->header();
        $inWechatpaySignature = $header['wechatpay-signature'];// 请根据实际情况获取
        $inWechatpayTimestamp = $header['wechatpay-timestamp'];// 请根据实际情况获取
        $inWechatpaySerial = $header['wechatpay-serial'];// 请根据实际情况获取
        $inWechatpayNonce = $header['wechatpay-nonce'];// 请根据实际情况获取
        $inBody = file_get_contents('php://input');;// 请根据实际情况获取，例如: file_get_contents('php://input');

        $apiv3Key = 'LJwJ1xpydN1nxQesJYnIQXuGDdKiFTae';// 在商户平台上设置的APIv3密钥

        // 根据通知的平台证书序列号，查询本地平台证书文件，
        // 假定为 `/path/to/wechatpay/inWechatpaySerial.pem`
        $platformPublicKeyInstance = Rsa::from('file:///www/wwwroot/hainan.megmt.com/public/wechatpay_77A215B745C4B7817B7DC820BD8AFC579779FB5C.pem', Rsa::KEY_TYPE_PUBLIC);

        // 检查通知时间偏移量，允许5分钟之内的偏移
        $timeOffsetStatus = 300 >= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);
        $verifiedStatus = Rsa::verify(
        // 构造验签名串
            Formatter::joinedByLineFeed($inWechatpayTimestamp, $inWechatpayNonce, $inBody),
            $inWechatpaySignature,
            $platformPublicKeyInstance
        );
        if ($timeOffsetStatus && $verifiedStatus) {
            // 转换通知的JSON文本消息为PHP Array数组
            $inBodyArray = (array)json_decode($inBody, true);
            // 使用PHP7的数据解构语法，从Array中解构并赋值变量
            ['resource' => [
                'ciphertext'      => $ciphertext,
                'nonce'           => $nonce,
                'associated_data' => $aad
            ]] = $inBodyArray;
            // 加密文本消息解密
            $inBodyResource = AesGcm::decrypt($ciphertext, $apiv3Key, $nonce, $aad);
            // 把解密后的文本转换为PHP Array数组
            $inBodyResourceArray = (array)json_decode($inBodyResource, true);
            // print_r($inBodyResourceArray);// 打印解密后的结果
            if(isset($inBodyResourceArray['trade_state'])&&$inBodyResourceArray['trade_state']=='SUCCESS'){
                $out_trade_no = $inBodyResourceArray['out_trade_no'];
                $sanfang = isset($inBodyResourceArray['transaction_id']) ? $inBodyResourceArray['transaction_id'] : '';
                Order::pay_success($out_trade_no,$sanfang,'微信');

//                $find = Order::where(['order_no'=>$out_trade_no])->find();
//                if($find){
//                    Order::where(['order_no'=>$out_trade_no])->update(['sanfang'=>$sanfang,'pay_status'=>2]);
//                }
                Test::create(['title'=>'微信回调解密','content'=>json_encode($inBodyResourceArray),'activitytime'=>date('Y-m-d H:i:s')]);
            }else{
                Test::create(['title'=>'微信回调解密-支付失败','content'=>json_encode($inBodyResourceArray),'activitytime'=>date('Y-m-d H:i:s')]);
            }


        }


        $this->success("成功", '成功');
    }

    //微信退款回调
    public function wxrefundcallback(){
        $all = $this->request->param();
        $header = $this->request->header();
        Test::create(['title'=>'微信退款回调','content'=>json_encode($all).'++'.json_encode($header),'activitytime'=>date('Y-m-d H:i:s')]);

        $inWechatpaySignature = $header['wechatpay-signature'];// 请根据实际情况获取
        $inWechatpayTimestamp = $header['wechatpay-timestamp'];// 请根据实际情况获取
        $inWechatpaySerial = $header['wechatpay-serial'];// 请根据实际情况获取
        $inWechatpayNonce = $header['wechatpay-nonce'];// 请根据实际情况获取
        $inBody = file_get_contents('php://input');;// 请根据实际情况获取，例如: file_get_contents('php://input');

        $apiv3Key = 'LJwJ1xpydN1nxQesJYnIQXuGDdKiFTae';// 在商户平台上设置的APIv3密钥

        // 根据通知的平台证书序列号，查询本地平台证书文件，
        // 假定为 `/path/to/wechatpay/inWechatpaySerial.pem`
        $platformPublicKeyInstance = Rsa::from('file:///www/wwwroot/hainan.megmt.com/public/wechatpay_77A215B745C4B7817B7DC820BD8AFC579779FB5C.pem', Rsa::KEY_TYPE_PUBLIC);

        // 检查通知时间偏移量，允许5分钟之内的偏移
        $timeOffsetStatus = 300 >= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);
        $verifiedStatus = Rsa::verify(
        // 构造验签名串
            Formatter::joinedByLineFeed($inWechatpayTimestamp, $inWechatpayNonce, $inBody),
            $inWechatpaySignature,
            $platformPublicKeyInstance
        );
        if ($timeOffsetStatus && $verifiedStatus) {
            // 转换通知的JSON文本消息为PHP Array数组
            $inBodyArray = (array)json_decode($inBody, true);
            // 使用PHP7的数据解构语法，从Array中解构并赋值变量
            ['resource' => [
                'ciphertext'      => $ciphertext,
                'nonce'           => $nonce,
                'associated_data' => $aad
            ]] = $inBodyArray;
            // 加密文本消息解密
            $inBodyResource = AesGcm::decrypt($ciphertext, $apiv3Key, $nonce, $aad);
            // 把解密后的文本转换为PHP Array数组
            $inBodyResourceArray = (array)json_decode($inBodyResource, true);
            // print_r($inBodyResourceArray);// 打印解密后的结果
            //退款逻辑处理
            Test::create(['title'=>'微信退款回调解密','content'=>json_encode($inBodyResourceArray),'activitytime'=>date('Y-m-d H:i:s')]);
            if($inBodyResourceArray['refund_status'] == 'ABNORMAL'){
                Order::where(['order_no'=>$inBodyResourceArray['out_trade_no']])->update(['pay_status'=>2]);
            }
            \app\admin\model\OrderRefunds::where(['out_order_id'=>$inBodyResourceArray['out_refund_no']])->update(['status'=>$inBodyResourceArray['refund_status']]);
        }


        $this->success("成功", '成功');
    }

    //个推
    public function send_gt(){
        $getui = new Getui();

        $payload = [
            'request_id' => uniqid(),
            'audience' => ['cid' => ['abc123']],
            'push_message' => [
                'notification' => [
                    'title' => '标题',
                    'body'  => '内容',
                ],
            ],
        ];
        $result = $getui->pushToSingle($payload);
        $this->success('推送消息',$result);
    }
}
